/**
 * 
 */
package com.wayoos.wap.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author steph
 * 
 */
public class UnzipUtils {

	public static final void main(String[] args) {
		/**
		 * Initialize the default parameters
		 */
		String zipFileName = "/Users/steph/Documents/workspace-wayoos-indigo/wayoos-wap/wap-distribution/target/apps/wap-registry-1.0.0-SNAPSHOT.zip";
		String directoryToExtractTo = "/Users/steph/Documents/workspace-wayoos-indigo/wayoos-wap/wap-distribution/target/apps/registry";

		/**
		 * Call the unzip method
		 */
		unzipMyZip(new File(zipFileName), new File(directoryToExtractTo));

	}

	/**
	 * This method --Reads an input stream --Writes the value to the output
	 * stream --Uses 1KB buffer.
	 */
	public static final void writeFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int len;

		while ((len = in.read(buffer)) >= 0)
			out.write(buffer, 0, len);

		in.close();
		out.close();
	}

	public static void unzipMyZip(File zipFileName, File directoryToExtractTo) {
		Enumeration<? extends ZipEntry> entries;
		ZipFile zipFile;
		try {
			File directory = directoryToExtractTo;
			if (!directory.exists()) {
				directory.mkdir();
			}
			zipFile = new ZipFile(zipFileName);
			entries = zipFile.entries();

			while (entries.hasMoreElements()) {
				try {
					ZipEntry entry = entries.nextElement();

					System.out.println(entry);

					if (entry.isDirectory()) {
						new File(directory, entry.getName()).mkdirs();
					} else {
						String name = entry.getName();

						writeFile(zipFile.getInputStream(entry), new FileOutputStream(new File(
								directory, name)));

					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			zipFile.close();
		} catch (IOException ioe) {
			System.err.println("Some Exception Occurred:");
			ioe.printStackTrace();
			return;
		}
	}
}